package osu.cloudmonitor;

import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Monitor {
	
	private static PrintWriter writer = null;
	private static String host = null;
	private static String logDir = null;
	private static String localID = null;
	private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static long lastCreateWriterTime = 0;
	private final static long createWriterInterval = 1000L * 60L * 60L * 24L; //one day
	
	private static void createWriter() throws Exception{
		if(System.currentTimeMillis() - lastCreateWriterTime < createWriterInterval)
			return;
		lastCreateWriterTime = System.currentTimeMillis();
		Date date = new Date();
		String logFile = logDir + File.separator + localID+" to "+host+" "+dateFormat.format(date);
		if(writer!=null){
			writer.close();
		}
		writer = new PrintWriter(new BufferedWriter(new FileWriter(logFile)));
		//System.out.println("created writer "+logFile);
	}
	
	public static void main(String []args) throws Exception{
		if(args.length != 5){
			System.out.println("java Monitor <host> <port> <packetSize> <logDir> <localID>");
			return;
		}
		host = args[0];
		int port = Integer.parseInt(args[1]);
		int packetSize = Integer.parseInt(args[2]);
		logDir = args[3];
		localID = args[4];
		byte[] readBuf = new byte[packetSize];
		
		
		while(true){
			try{
				createWriter();
				long start = System.currentTimeMillis();
				Socket socket = new Socket(host, port);
				DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
				dos.writeInt(packetSize);
				dos.flush();
				DataInputStream dis = new DataInputStream(socket.getInputStream());
				dis.readFully(readBuf);
				Date date = new Date();
				writer.print(dateFormat.format(date)+" lat=");
				writer.print(String.valueOf(System.currentTimeMillis() - start));
				writer.println();
				writer.flush();
				socket.close();
				Thread.sleep(Configuration.RETRY_TIMEOUT);
			}
			catch(Exception e){
				Date date = new Date();
				writer.println(dateFormat.format(date));
				e.printStackTrace(writer);
				writer.flush();
				try{
					Thread.sleep(Configuration.RETRY_TIMEOUT);
				}
				catch(InterruptedException ie){}
			}
		}
	}
}
